<template>
  <div class="page-container">
    <div class="d-flex justify-content-between align-items-center mb-4">
      <h2>新建项目</h2>
      <button class="btn btn-outline-secondary" @click="goBack">
        <i class="bi bi-arrow-left me-1"></i> 返回项目列表
      </button>
    </div>

    <div class="card">
      <div class="card-body">
        <form @submit.prevent="submitForm">
          <!-- 表单分组：基本信息 -->
          <div class="form-section mb-4">
            <h4 class="form-section-title">基本信息</h4>
            <div class="row g-3">
              <div class="col-md-4">
                <label class="form-label required">项目名称</label>
                <input type="text" class="form-control" v-model="formData.name" required>
                <div class="invalid-feedback" v-if="errors.name">{{ errors.name }}</div>
              </div>
              <div class="col-md-4">
                <label class="form-label required">项目编号</label>
                <input type="text" class="form-control" v-model="formData.project_code" required>
                <div class="invalid-feedback" v-if="errors.project_code">{{ errors.project_code }}</div>
              </div>
              <div class="col-md-4">
                <label class="form-label">项目序号</label>
                <input type="number" class="form-control" v-model="formData.project_number">
              </div>
              <div class="col-md-4">
                <label class="form-label required">项目阶段</label>
                <select class="form-select" v-model="formData.status" required>
                  <option value="">请选择项目阶段</option>
                  <option v-for="status in projectStatusOptions" :key="status" :value="status">{{ status }}</option>
                </select>
                <div class="invalid-feedback" v-if="errors.status">{{ errors.status }}</div>
              </div>
              <div class="col-md-4">
                <label class="form-label">阶段状态</label>
                <select class="form-select" v-model="formData.phase_status">
                  <option value="">请选择阶段状态</option>
                  <option v-for="status in phaseStatusOptions" :key="status" :value="status">{{ status }}</option>
                </select>
              </div>
              <div class="col-md-4">
                <label class="form-label">建设地点</label>
                <input type="text" class="form-control" v-model="formData.location" placeholder="多个地点用逗号分隔">
              </div>
              <div class="col-12">
                <label class="form-label">项目描述/建设内容</label>
                <textarea class="form-control" v-model="formData.description" rows="3"></textarea>
              </div>
            </div>
          </div>

          <!-- 表单分组：任务书信息 -->
          <div class="form-section mb-4">
            <h4 class="form-section-title">任务书信息</h4>
            <div class="row g-3">
              <div class="col-md-4">
                <label class="form-label">任务书文号</label>
                <input type="text" class="form-control" v-model="formData.task_document_no">
              </div>
              <div class="col-md-4">
                <label class="form-label">规划类型</label>
                <input type="text" class="form-control" v-model="formData.planning_type">
              </div>
              <div class="col-md-4">
                <label class="form-label">建设类型</label>
                <select class="form-select" v-model="formData.construction_type">
                  <option value="">请选择建设类型</option>
                  <option v-for="type in constructionTypeOptions" :key="type" :value="type">{{ type }}</option>
                </select>
              </div>
              <div class="col-md-4">
                <label class="form-label">任务书下达时间</label>
                <input type="date" class="form-control" v-model="formData.task_issue_date">
              </div>
              <div class="col-md-4">
                <label class="form-label">任务书要求完成时间</label>
                <input type="date" class="form-control" v-model="formData.required_completion_date">
              </div>
              <div class="col-md-4">
                <label class="form-label">上级延期完成时间</label>
                <input type="date" class="form-control" v-model="formData.extended_completion_date">
              </div>
              <div class="col-md-4">
                <label class="form-label">总投资(万元)</label>
                <input type="number" class="form-control" v-model="formData.total_investment" step="0.01">
              </div>
              <div class="col-md-4">
                <label class="form-label">直接费(万元)</label>
                <input type="number" class="form-control" v-model="formData.direct_cost" step="0.01">
              </div>
            </div>
          </div>

          <!-- 表单分组：合同信息 -->
          <div class="form-section mb-4">
            <h4 class="form-section-title">合同信息</h4>
            <div class="row g-3">
              <div class="col-md-4">
                <label class="form-label">发包模式</label>
                <select class="form-select" v-model="formData.bidding_mode">
                  <option value="">请选择发包模式</option>
                  <option v-for="mode in biddingModeOptions" :key="mode" :value="mode">{{ mode }}</option>
                </select>
              </div>
              <div class="col-md-4">
                <label class="form-label">合同开工日期</label>
                <input type="date" class="form-control" v-model="formData.contract_start_date">
              </div>
              <div class="col-md-4">
                <label class="form-label">合同竣工日期</label>
                <input type="date" class="form-control" v-model="formData.contract_end_date">
              </div>
              <div class="col-md-4">
                <label class="form-label">合同工期(天)</label>
                <input type="number" class="form-control" v-model="formData.contract_duration">
              </div>
              <div class="col-md-4">
                <label class="form-label">施工合同价(万元)</label>
                <input type="number" class="form-control" v-model="formData.contract_amount" step="0.01">
              </div>
            </div>
          </div>

          <!-- 表单分组：参建单位信息 -->
          <div class="form-section mb-4">
            <h4 class="form-section-title">参建单位信息</h4>
            <div class="row g-3">
              <div class="col-md-4">
                <label class="form-label">设计单位</label>
                <input type="text" class="form-control" v-model="formData.design_unit">
              </div>
              <div class="col-md-4">
                <label class="form-label">造价编制单位</label>
                <input type="text" class="form-control" v-model="formData.cost_compilation_unit">
              </div>
              <div class="col-md-4">
                <label class="form-label">造价审核单位</label>
                <input type="text" class="form-control" v-model="formData.cost_audit_unit">
              </div>
              <div class="col-md-4">
                <label class="form-label">施工单位</label>
                <input type="text" class="form-control" v-model="formData.construction_unit">
              </div>
              <div class="col-md-4">
                <label class="form-label">监理单位</label>
                <input type="text" class="form-control" v-model="formData.supervision_unit">
              </div>
              <div class="col-md-4">
                <label class="form-label">使用单位</label>
                <input type="text" class="form-control" v-model="formData.using_unit">
              </div>
              <div class="col-md-4">
                <label class="form-label">代供单位</label>
                <input type="text" class="form-control" v-model="formData.supply_unit">
              </div>
            </div>
          </div>

          <!-- 表单分组：联系信息 -->
          <div class="form-section mb-4">
            <h4 class="form-section-title">联系信息</h4>
            <div class="row g-3">
              <div class="col-md-6">
                <label class="form-label">现场联系人</label>
                <input type="text" class="form-control" v-model="formData.field_contact">
              </div>
              <div class="col-md-6">
                <label class="form-label">联系电话</label>
                <input type="text" class="form-control" v-model="formData.contact_phone">
              </div>
            </div>
          </div>

          <!-- 表单分组：其他信息 -->
          <div class="form-section mb-4">
            <h4 class="form-section-title">其他信息</h4>
            <div class="row g-3">
              <div class="col-12">
                <label class="form-label">备注信息</label>
                <textarea class="form-control" v-model="formData.notes" rows="3"></textarea>
              </div>
            </div>
          </div>

          <!-- 提交按钮 -->
          <div class="d-flex justify-content-end mt-4">
            <button type="button" class="btn btn-outline-secondary me-2" @click="resetForm">
              <i class="bi bi-arrow-counterclockwise me-1"></i> 重置表单
            </button>
            <button type="submit" class="btn btn-primary" :disabled="isSubmitting">
              <i class="bi bi-check-circle me-1"></i> 
              <span v-if="isSubmitting">提交中...</span>
              <span v-else>创建项目</span>
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'

// 获取router实例
const router = useRouter()

// 表单数据
const formData = reactive({
  project_number: null,
  project_code: '',
  name: '',
  description: '',
  location: '',
  status: '',
  sub_status: '',
  progress: 0,
  phase_status: '',
  task_document_no: '',
  planning_type: '',
  construction_type: '',
  total_investment: null,
  direct_cost: null,
  task_issue_date: '',
  required_completion_date: '',
  extended_completion_date: '',
  contract_start_date: '',
  contract_end_date: '',
  contract_duration: null,
  contract_amount: null,
  bidding_mode: '',
  design_unit: '',
  cost_compilation_unit: '',
  cost_audit_unit: '',
  construction_unit: '',
  supervision_unit: '',
  using_unit: '',
  supply_unit: '',
  field_contact: '',
  contact_phone: '',
  notes: ''
})

// 表单错误信息
const errors = reactive({})

// 提交状态
const isSubmitting = ref(false)

// 选项数据
const projectStatusOptions = ref([])
const phaseStatusOptions = ref(['正常进行', '阶段性迟缓', '滞后'])
const biddingModeOptions = ref(['招标', '直接委托'])
const constructionTypeOptions = ref(['统建', '代建'])

// 获取系统设置
async function fetchSettings() {
  try {
    const response = await window.api.database.getSettings('project')
    
    if (response.success) {
      // 获取项目状态选项
      const projectStatusSetting = response.data.find(item => item.key === 'default_project_status')
      if (projectStatusSetting && projectStatusSetting.value) {
        projectStatusOptions.value = projectStatusSetting.value.split(',')
      }
      
      // 获取阶段状态选项
      const phaseStatusSetting = response.data.find(item => item.key === 'default_phase_status')
      if (phaseStatusSetting && phaseStatusSetting.value) {
        phaseStatusOptions.value = phaseStatusSetting.value.split(',')
      }
      
      // 获取发包模式选项
      const biddingModeSetting = response.data.find(item => item.key === 'default_bidding_modes')
      if (biddingModeSetting && biddingModeSetting.value) {
        biddingModeOptions.value = biddingModeSetting.value.split(',')
      }
      
      // 获取建设类型选项
      const constructionTypeSetting = response.data.find(item => item.key === 'default_construction_types')
      if (constructionTypeSetting && constructionTypeSetting.value) {
        constructionTypeOptions.value = constructionTypeSetting.value.split(',')
      }
    }
  } catch (error) {
    console.error('获取系统设置失败:', error)
  }
}

// 提交表单
async function submitForm() {
  // 清除之前的错误信息
  Object.keys(errors).forEach(key => delete errors[key])
  
  // 表单验证
  let isValid = true
  
  // 必填字段验证
  if (!formData.name) {
    errors.name = '项目名称不能为空'
    isValid = false
  }
  
  if (!formData.project_code) {
    errors.project_code = '项目编号不能为空'
    isValid = false
  }
  
  if (!formData.status) {
    errors.status = '项目阶段不能为空'
    isValid = false
  }
  
  if (!isValid) {
    return
  }
  
  try {
    isSubmitting.value = true
    
    // 调用API创建项目
    const response = await window.api.database.createProject({
      ...formData,
      progress: formData.progress || 0
    })
    
    if (response.success) {
      // 创建成功，跳转到项目详情页
      router.push(`/project-detail/${response.data.id}`)
    } else {
      // 创建失败，显示错误信息
      if (response.error.includes('UNIQUE constraint failed: projects.project_code')) {
        errors.project_code = '项目编号已存在，请使用其他编号'
      } else {
        alert(`创建项目失败: ${response.error}`)
      }
    }
  } catch (error) {
    console.error('创建项目失败:', error)
    alert(`创建项目失败: ${error.message}`)
  } finally {
    isSubmitting.value = false
  }
}

// 重置表单
function resetForm() {
  // 重置表单数据
  Object.keys(formData).forEach(key => {
    if (typeof formData[key] === 'string') {
      formData[key] = ''
    } else if (typeof formData[key] === 'number') {
      formData[key] = null
    }
  })
  
  // 设置默认值
  formData.progress = 0
  formData.phase_status = '正常进行'
  
  // 清除错误信息
  Object.keys(errors).forEach(key => delete errors[key])
}

// 返回项目列表
function goBack() {
  router.push('/projects')
}

// 生命周期钩子
onMounted(async () => {
  await fetchSettings()
})
</script>

<style scoped>
.form-section {
  border: 1px solid #e9ecef;
  border-radius: 0.25rem;
  padding: 1.5rem;
  background-color: #f8f9fa;
}

.form-section-title {
  margin-top: -2.5rem;
  margin-bottom: 1rem;
  background-color: #fff;
  display: inline-block;
  padding: 0.5rem 1rem;
  border: 1px solid #e9ecef;
  border-radius: 0.25rem;
  font-size: 1.1rem;
  font-weight: 600;
}

.required::after {
  content: " *";
  color: #dc3545;
}

.invalid-feedback {
  display: block;
}
</style> 